<template>
  
  <!-- <div class="hello"> -->
      <h1>count is {{count}}</h1>
      <h2>double count is {{double}}</h2>
      <button @click="add">click</button>
      <input type="text" v-model="state.newTodos" @keyup.enter="addNewTodo">
      <ul>
        <li v-for="todo in state.todos" :key="todo">{{todo}}</li>
      </ul>
  
</template>

<script>
import {ref, computed,onMounted,watchEffect, reactive} from 'vue'
//上面这个写法很好的支持tree-shaking
export default {
  // setup(){
  //   let count = ref(0)
  //   function add(){
  //     count.value++
  //   }
  //   const double = computed(()=>count.value*2)
  //   return {count,double,add}
  // }
  // 换一种写法
  // setup(){
    


  //   return {count,double,add}
  // },
  setup(){
    //reactive把对象变成响应式
    const {count,double,add} = useCount(1)
    const state = reactive({
      newTodos:'',
      todos:[
        {id:'1',title:'吃西瓜',computed:false},
        {id:'2',title:'吃麻辣烫',computed:false},
        {id:'3',title:'学习vue3',computed:false},
        {id:'1',title:'吃西瓜',computed:false},
        {id:'2',title:'吃麻辣烫',computed:false},
        {id:'3',title:'学习vue3',computed:false},
        {id:'1',title:'吃西瓜',computed:false},
        {id:'2',title:'吃麻辣烫',computed:false},
        {id:'3',title:'学习vue3',computed:false},
        {id:'1',title:'吃西瓜',computed:false},
        {id:'2',title:'吃麻辣烫',computed:false},
        {id:'3',title:'学习vue3',computed:false},
      ]
    })
    function addNewTodo(){
      const val = state.newTodos
      if(!val){
        return
      }
      state.todos.push({
        id:state.todos.length+1,
        title:val,
        computed:false,
      })
      state.newTodos = ''
    }
    return {state,count,double,add,addNewTodo}
  }
}
//可以单独拆成文件，取代vue2中的mixin
function useCount(init){
    let count = ref(init)
    function add(){
      count.value++
    }
    const double = computed(()=>count.value*2)
    onMounted(()=>{
      console.log('onMounted')
    })
    watchEffect(()=>{
      console.log('count is ',count.value)
    })
    return {count,double,add}

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
